namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    using System.Web;

    /// <summary>
    /// 1. Start at Sales homepage
    /// 2. Select Accounts
    /// 3. Select Active Accounts View
    /// 4. Enter a random string and click "Find"
    /// 5. Open an account and edit data
    /// 6. Save and Close account
    /// </summary>

    public class UpdateAccount : CrmWebTest
    {
        public void UpdateAccount_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
            
			EntityRequest AccountEr = new EntityRequest();
			AccountEr.Type = EntityNames.Accounts;
			AccountEr.ParentID = Guid.NewGuid();
			AccountEr.ReturnAs = EntityNames.Accounts;

			Props.Add(EntityNames.Accounts, new EntityRequest[] { AccountEr });

			er.Props = Props;

			System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			account = (CRMEntity)Entities[EntityNames.Accounts];

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
            
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);            
        }
        
        public void UpdateAccount_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            EntityManager.Instance.FreeEntity(user);
            EntityManager.Instance.FreeEntity(account);
        }

        public UpdateAccount()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            string random = Utils.GetRandomString(2, 2);
            gridXml = GridXmlHelper.AccountPageView(-1, activeAccountsView, null);
            gridXml2 = GridXmlHelper.AccountSearchView(-1, searchAccountsView, random, null);
            gridRefreshXml = GridXmlHelper.AccountPageSearchViewRefresh(-1, searchAccountsView, random, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(UpdateAccount_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(UpdateAccount_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            AppGridWebService.AppGridWebService ag;
            WebTestRequest wtr;

			this.BeginTransaction("NavAccountHomepage");

            // Get the home page
            _root_homepage_aspx hp = new _root_homepage_aspx(user);
            hp.etc = 1;
            yield return (hp);

			this.EndTransaction("NavAccountHomepage");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavActiveAccounts");

                // Grid with All Accounts
                ag = new AppGridWebService.AppGridWebService();
                wtr = null;

                try { ag.Reset(gridXml, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavActiveAccounts");
            }

            this.BeginTransaction("SearchAccounts");

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;

            try { ag.Reset(gridXml2, gridId); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);
                
                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("SearchAccounts");

            this.BeginTransaction("OpenAccount");

            sfa_accts_edit_aspx dp = new sfa_accts_edit_aspx(user);
            dp.id = account["accountid"];
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx formScript = new _forms_FormScript_js_aspx(user);
            formScript.etc = 1;
            formScript.FormType = "main";
            formScript.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            formScript.Headers.Add(headerItem);
            yield return (formScript);

            _controls_number_formatNumber_xsl format = new _controls_number_formatNumber_xsl(crmServer);
            yield return (format);

            this.EndTransaction("OpenAccount");

            this.BeginTransaction("UpdateAccount");

            dp = new sfa_accts_edit_aspx(user);
            // QueryString Parameters
            dp.id = account["accountid"];

            // Form Parameters
            dp.crmFormSubmitXml = EntityXmlHelper.GetUpdateAccountXml();

            rpcInfo = Utils.GenerateWRPCToken(sfa_accts_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            dp.crmFormSubmitMode = 2;
            dp.crmFormSubmitId = account["accountid"];
            dp.CrmFormUserModified = true;
            dp.crmFormSubmitObjectType = 1;
            dp.crmFormSubmitSecurity = 852023;
            dp.crmFormSubmitOnline = 1;
            yield return (dp);
                        
            AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
            WebTestRequest wtrRefresh = null;
            try { agws.Refresh(gridRefreshXml); }
            catch (crmException x)
            {
                wtrRefresh = x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);
                wtrRefresh.Encoding = Encoding.UTF8;

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            this.EndTransaction("UpdateAccount");
        }

        private string gridXml;
        private string gridXml2;
        private string gridRefreshXml;
        private static string gridId = "crmGrid";
        private static string activeAccountsView = "00000000-0000-0000-00AA-000010001002";
        private static string searchAccountsView = "2D1187C4-23FE-4BB5-9647-43BB1C6DDBD1";

        private CRMEntity user;
        private CRMEntity account;
        private string crmServer;
        private string tokenKey;
        private Guid orgId;

        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
        private string referer;
    }
}